<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>背景移动</title>
    <style type="text/css">
        body{
            background: #ddd;
        }

        #canvas{
            position: absolute;
            top:30px;
            left:10px;
            background: #fff;
            cursor:crosshair;
            margin-left: 10px;
            margin-top: 10px;
            box-shadow: 4px 4px 8px rgba(0,0,0,.5);
        }

        input{
            margin-left: 15px;
        }

    </style>
</head>
<body>

<canvas id="canvas" width=600 height=400>Canvas not supported</canvas>

<input id="animateButton", type="button" value="Animate">


<script>
(function(){

var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),

    animateButton = document.getElementById("animateButton"),
    sky = new Image(),

    paused = true,
    lastTime = 0,
    fps = 0,
    skyOffset = 0,
    SKY_VELOCITY = 10;

function erase(){
    context.clearRect(0,0,canvas.width,canvas.height);
}

function draw(){
    skyOffset = skyOffset < canvas.width?skyOffset + 1:0;
    context.save();
    context.translate(-skyOffset, 0);
    context.drawImage(sky, 0, 0);
    context.drawImage(sky, sky.width-2,0);
    context.restore();
}

function caculateFps(now){
    var fps = 1000/(now - lastTime);
    lastTime = now;
    return fps;
}

function animate(now){
    if(now === undefined){
        now = +new Date;
    }

    fps = caculateFps(now);

    if(!paused){
        erase();
        draw();
    }

    requestAnimationFrame(animate);
}

animateButton.onclick = function(){
    paused = paused?false:true;
    if(paused){
        animateButton.value="Animate";
    }else{
        animateButton.value = "Pause";
    }
}


canvas.width=canvas.width;
canvas.height = canvas.height;

sky.src = "sky.jpg";
sky.onload = function(e){
    draw();
}
requestAnimationFrame(animate);

}());
</script>
</body>
</html>